const func = (str, time) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(str, time);
            resolve(str);
        }, time || 2000);
    });
}

class execList {
    #waitWorkList = [];
    #listLength = 3;
    #running = 0;

    constructor(options = {}) {
        this.#listLength = options.listLength || 3;
    }

    #run() {
        while (this.#running < this.#listLength && this.#waitWorkList.length) {
            const { task, resolve, reject } = this.#waitWorkList.shift();
            this.#running = this.#running + 1;
            task().then(resolve, reject).finally(() => {
                this.#running = this.#running - 1;
                this.#run();
            })
        }
    }

    add(task) {
        return new Promise((resolve, reject) => {
            this.#waitWorkList.push({
                task, resolve, reject
            })
            this.#run();
        })
    }
}

const execListObj = new execList();
const add = (str, time) => {
    execListObj.add(() => { return func(str, time) })
        .then((res) => console.log(`任务完成`, res))
}


add(1, 10000);
add(2, 5000);
add(3, 1000);
add(4, 5000);
add(5, 1000);
add(6, 3000);
add(7, 1000);
add(8, 1000);
add(9, 7000);
add(10, 1000);
add(11, 1000);
add(12, 1000);
add(12, 8000);
add(14, 1000);
add(15, 3000);
add(16, 1000);
add(17, 2000);
add(18, 1000);
add(19, 1000);
add(20, 1000);
add(21, 1000);